package com.self.cloudmall.wms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.self.cloudmall.common.dto.ReceAddressDto;
import com.self.cloudmall.common.utils.R;
import com.self.cloudmall.wms.client.MemberClient;
import com.self.cloudmall.common.dto.ReceAddrFareDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.self.cloudmall.wms.utils.PageUtils;
import com.self.cloudmall.wms.utils.Query;

import com.self.cloudmall.wms.mapper.WareInfoMapper;
import com.self.cloudmall.wms.entity.WareInfoEntity;
import com.self.cloudmall.wms.service.WareInfoService;


@Slf4j
@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoMapper, WareInfoEntity> implements WareInfoService {

    @Autowired
    private MemberClient memberClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                new QueryWrapper<WareInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<WareInfoEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(key)){
            queryWrapper.and(w -> w.lambda().eq(WareInfoEntity::getId,key).or()
            .like(WareInfoEntity::getName,key)
            .like(WareInfoEntity::getAddress,key));
        }
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public ReceAddrFareDto getFare(Long addrId) {
        R r = memberClient.receiveAddressInfo(addrId);
        if (r.isSuccess()){
            ReceAddrFareDto receAddrFareVo = new ReceAddrFareDto();
            ReceAddressDto addressDto = JSONObject.parseObject(JSONObject.toJSONString(r.getData()), ReceAddressDto.class);
            receAddrFareVo.setReceAddress(addressDto);
            //运费需要物流公司提供，这就用地址的hash值与10取模
            Integer fare = addressDto.getDetailAddress().hashCode()%10;
            receAddrFareVo.setFare(new BigDecimal(fare));
            return receAddrFareVo;
        }
        log.error("获取收货方地址异常：{},收货ID：{}",JSONObject.toJSONString(r),addrId);
        return null;
    }

}